// 雪花效果控制器
class Snowfall {
  constructor() {
    this.snowflakes = [];
    this.isActive = false;
    this.settings = {
      density: 150,
      speed: 5,
      size: 10,
      color: '#e0e0e0', // 添加颜色默认值
      color2: '#ffffff', // 添加颜色默认值
      gradientType: 'linear', // 添加默认值
      shapeType: 'circle', // 添加默认值
      textValue: '', // 添加默认值
    };
    this.container = null;
    this.pileHeight = 0; // 新增：当前堆积高度

    // 从存储加载设置
    chrome.storage.sync.get(['isActive', 'density', 'speed', 'size', 'color', 'color2', 'gradientType', 'shapeType', 'textValue'], (result) => {
      if (result.isActive) {
        this.isActive = true;
        this.settings.density = result.density || 150;
        this.settings.speed = result.speed || 5;
        this.settings.size = result.size || 10;
        this.settings.color = result.color || '#e0e0e0';
        this.settings.color2 = result.color2 || '#ffffff';
        this.settings.gradientType = result.gradientType || 'linear';
        this.settings.shapeType = result.shapeType || 'circle';
        this.settings.textValue = result.textValue || '';
        this.start();
      }
    });
  }

  // 创建雪花容器
  createContainer() {
    if (this.container) return;

    this.container = document.createElement('div');
    this.container.style.position = 'fixed';
    this.container.style.top = '0';
    this.container.style.left = '0';
    this.container.style.width = '100%';
    this.container.style.height = '100%';
    this.container.style.pointerEvents = 'none';
    this.container.style.zIndex = '9999';
    document.body.appendChild(this.container);
  }

  // 创建雪花
  createSnowflake() {
    if(!this.container){//是否存在雪花容器
      this.createContainer();
    }

    const snowflake = document.createElement('div');
    snowflake.classList.add('snowflake');

    // 应用颜色设置
    // snowflake.style.backgroundColor = this.settings.color;

    // 渐变类型处理
    if (this.settings.gradientType === 'linear') {
      // 随机渐变角度增加变化性
      const angle = Math.random() * 360;
      snowflake.style.background = `linear-gradient(${angle}deg, ${this.settings.color}, ${this.settings.color2})`;
    } else {
      // 随机中心点位置（50%±30% 范围内）
      const centerX = 50 + (Math.random() * 60 - 30);
      const centerY = 50 + (Math.random() * 60 - 30);

      // 随机渐变形状（圆形/椭圆形）
      const shape = Math.random() > 0.5 ? 'circle' : 'ellipse';

      // 随机大小比例（50%-100%）
      const size = 50 + Math.random() * 50;
      const sizeParam = shape === 'circle' ? `${size}%` : `${size}% ${size * 0.8}%`; // 椭圆略扁

      // 径向渐变（从中心到边缘）
      snowflake.style.background = `radial-gradient( ${shape} ${sizeParam} at ${centerX}% ${centerY}%, ${this.settings.color}, ${this.settings.color2})`;
    }

    // 随机大小（基于设置的大小范围）
    const size = Math.random() * this.settings.size + 1;
    snowflake.style.width = `${size}px`;
    snowflake.style.height = `${size}px`;

    // 应用形状设置
    let finalShapeType = this.settings.shapeType;

    // 新增：随机形状模式
    if (finalShapeType === 'random') {
      const shapes = ['circle', 'square', 'star', 'heart', 'textValue'];
      finalShapeType = shapes[Math.floor(Math.random() * shapes.length)];
    }

    // 应用形状设置
    switch(finalShapeType) {
      case 'square':
        snowflake.style.borderRadius = '0';
        break;
      case 'star':
        snowflake.style.borderRadius = '0';
        snowflake.style.clipPath = 'polygon(50% 0%, 61% 35%, 98% 35%, 68% 57%, 79% 91%, 50% 70%, 21% 91%, 32% 57%, 2% 35%, 39% 35%)';
        break;
      case 'heart': // 爱心形状（正确路径）
        snowflake.style.borderRadius = '0';
          //动态计算心形路径
          const pathString = this.calculateHeartPath(size,size);
        // 调整后的爱心路径，path的值不能使用%但是可以直接
        snowflake.style.clipPath = `path('${pathString}')`;
        break;
      case 'textValue': // 文字
        snowflake.style.width = `auto`;
        snowflake.style.height = `${size}px`; // 关键修改：使用size作为高度
        snowflake.style.borderRadius = '0';
        snowflake.textContent = this.settings.textValue;

        // 设置文本字体属性
        snowflake.style.fontSize = `${size}px`;
        snowflake.style.fontWeight = 'bold';
        snowflake.style.fontFamily = 'Arial, sans-serif';

        // 确保文本居中显示
        snowflake.style.display = 'flex';
        snowflake.style.alignItems = 'center';
        snowflake.style.justifyContent = 'center';

        // 文本不换行处理
        snowflake.style.whiteSpace = 'nowrap';
        snowflake.style.overflow = 'hidden';

        // 应用文本渐变效果
        snowflake.style.color = 'transparent';
        snowflake.style.backgroundClip = 'text';
        snowflake.style.webkitBackgroundClip = 'text'; // 兼容WebKit浏览器
        break;
      default: // circle
        snowflake.style.borderRadius = '50%';
    }

    // 随机水平位置
    const startPosX = Math.random() * window.innerWidth;
    snowflake.style.left = `${startPosX}px`;

    // 随机不透明度
    const opacity = Math.random() * 0.5 + 0.3;
    snowflake.style.opacity = opacity;

    // 随机动画延迟和持续时间
    const delay = Math.random() * 10;
    const duration = (20 - this.settings.speed) + Math.random() * 10;

    // 设置动画
    snowflake.style.animation = `fall ${duration}s linear ${delay}s infinite`;

    this.container.appendChild(snowflake);
    this.snowflakes.push(snowflake);

    // 雪花动画结束后处理堆积效果
    snowflake.addEventListener('animationiteration', () => {
      // 堆积概率65%，总高不超过40%窗口
      if (Math.random() < 0.65 && this.pileHeight < window.innerHeight * 0.4) {
        snowflake.classList.add('snowflake-pile');//增加专属标志
        // 停止动画
        snowflake.style.animation = 'none';

        // 1. 随机水平位置（左右留5px边距，避免超出屏幕）
        const maxLeft = window.innerWidth - 10; // 右侧留5px
        const randomLeft = 5 + Math.random() * maxLeft; // 左侧留5px
        snowflake.style.left = `${randomLeft}px`;

        // 2. 垂直位置：从底部向上堆叠，允许±5px偏差（模拟不整齐堆叠）
        const baseBottom = window.innerHeight - this.pileHeight; // 基准底部位置
        const randomOffset = (Math.random() - 0.5) * 10; // -5px 到 +5px 随机偏差
        snowflake.style.top = `${baseBottom + randomOffset}px`;

        // 3. 累加堆积高度（用雪花自身高度的20%，避免堆太快）
        const snowHeight = parseInt(snowflake.style.height);
        const randomPile = (Math.random() - 0.1) * 0.3; // -0.1 到 0.2 随机偏差
        this.pileHeight += (snowHeight + randomPile) * 0.2;

        // 从活动雪花数组中移除
        const index = this.snowflakes.indexOf(snowflake);
        if (index > -1) this.snowflakes.splice(index, 1);
      } else {
        // 正常重置位置
        snowflake.style.left = `${Math.random() * window.innerWidth}px`;
        snowflake.style.top = '-10%';
      }
    });
  }

  // 清除所有雪花
  clearSnowflakes() {
    this.clearSnowflakesPile()
    this.clearSnowflakesDef()
  }

  clearSnowflakesDef() {
    this.snowflakes.forEach(snowflake => {
      if (snowflake.parentNode) {
        snowflake.parentNode.removeChild(snowflake);
      }
    });
    this.snowflakes = [];
  }

  clearSnowflakesPile() {
    // 修复：清除容器内雪花（堆积的）
    document.querySelectorAll('.snowflake-pile').forEach(snow => snow.remove());
    this.pileHeight = 0; // 重置堆积高度
  }

  // 开始飘雪
  start() {
    if (this.isActive) return;

    this.isActive = true;
    this.generateSnowflakes();
  }

  // 生成指定数量的雪花
  generateSnowflakes() {
    this.clearSnowflakes();

    // 根据密度创建雪花
    for (let i = 0; i < this.settings.density; i++) {
      // 分散创建雪花，避免同时出现
      setTimeout(() => this.createSnowflake(), i * 100);
    }
  }

  // 停止飘雪
  stop() {
    if (!this.isActive) return;

    this.isActive = false;
    this.clearSnowflakes();

    if (this.container && this.container.parentNode) {
      this.container.parentNode.removeChild(this.container);
      this.container = null;
    }

    this.pileHeight = 0; // 重置堆积高度
  }

  // 更新雪花设置
  updateSettings(settings) {
    this.settings = { ...this.settings, ...settings };

    if (this.isActive) {
      this.generateSnowflakes();
    }
  }

    // 根据容器尺寸计算实际路径
  calculateHeartPath(width,height) {
    // 爱心的百分比路径点（基于100%宽度和100%高度）
    const heartPathPoints = [
        { type: 'M', x: 0.5, y: 0.2 },      // 起点：50%, 20%
        { type: 'C', x1: 0.4, y1: 0.0, x2: 0.0, y2: 0.1, x: 0.2, y: 0.4 },  // 左侧曲线控制点
        { type: 'C', x1: 0.3, y1: 0.5, x2: 0.5, y2: 0.7, x: 0.5, y: 0.7 },  // 底部控制点
        { type: 'C', x1: 0.5, y1: 0.7, x2: 0.7, y2: 0.5, x: 0.8, y: 0.4 },  // 右侧控制点
        { type: 'C', x1: 1.0, y1: 0.1, x2: 0.6, y2: 0.0, x: 0.5, y: 0.2 },  // 顶部控制点
        { type: 'Z' }  // 闭合路径
    ];

    let pathString = '';

    // 处理每个路径点
    heartPathPoints.forEach(point => {
        switch (point.type) {
            case 'M':
                pathString += `M ${Math.round(point.x * width)} ${Math.round(point.y * height)} `;
                break;
            case 'C':
                pathString += `C ${Math.round(point.x1 * width)} ${Math.round(point.y1 * height)}, `;
                pathString += `${Math.round(point.x2 * width)} ${Math.round(point.y2 * height)}, `;
                pathString += `${Math.round(point.x * width)} ${Math.round(point.y * height)} `;
                break;
            case 'Z':
                pathString += 'Z';
                break;
        }
    });

    return pathString;
  }
}

// 初始化雪花效果
const snowfall = new Snowfall();

// 监听来自popup的消息
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
  console.log("应用页打印",message, sender, sendResponse);
  switch (message.action) {
    case 'startSnow':
      snowfall.updateSettings({...message});
      snowfall.start();
      break;
    case 'stopSnow':
      snowfall.stop();
      break;
    case 'updateSnow':
      snowfall.updateSettings({...message});
      break;
  }
});
